<template>
  <div class="pwdLogin">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" status-icon label-width="70px" class="demo-ruleForm">
      <el-form-item label="原密码" prop="oldpass">
        <el-input v-model="ruleForm.oldpass" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newpass">
        <el-input v-model="ruleForm.newpass" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="ruleForm.checkPass" type="password" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native="submitForm">修改</el-button>
        <el-button @click.native="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { editLoginPwd } from '@/api/table'
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }

    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else if (value !== this.ruleForm.newpass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        oldpass: '',
        newpass: '',
        checkPass: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          editLoginPwd({
            password: this.ruleForm.oldpass,
            newPassword: this.ruleForm.newpass
          }).then(response => {
            this.$message({
              message: '修改登录密码成功',
              type: 'success'
            })
            this.resetForm()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.pwdLogin{
  padding: 30px;
  width: 500px;
  max-width: 100%;
}
</style>
